package com.leonyip.firstdemo.service.impl;

import com.leonyip.firstdemo.dao.UserDao;
import com.leonyip.firstdemo.entity.User;
import com.leonyip.firstdemo.entity.UserExample;
import com.leonyip.firstdemo.service.UserServie;
import com.leonyip.firstdemo.utils.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
@Service
public class UserServiceImpl implements UserServie {
    @Autowired
    private UserDao userDao;
    @Override
    public List<User> getAll() {
        return userDao.selectByExample(null);
    }

    @Override
    public User getById(Integer id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public List<User> findByUserName(String userName) {
        UserExample example = new UserExample();
        example.createCriteria().andUserNameLike("%"+userName+"%");
        List<User> list = userDao.selectByExample(example);
        return list;
    }

    @Override
    public PageInfo<User> getByPage(int pageNum, int pageSize) {
        UserExample example = new UserExample();
        example.setOffset((long) (pageSize*(pageNum-1)));
        example.setLimit(pageSize);
       List<User> list=userDao.selectByExample(example);

       long total =userDao.countByExample(null);

       PageInfo<User> pageInfo=new PageInfo<>();
       pageInfo.setPageNum(pageNum);
       pageInfo.setPageSize(pageSize);
       pageInfo.setTotal(total);
       pageInfo.setData(list);

       return pageInfo;
    }
    @Override
    public int update(User user) {
        return userDao.updateByPrimaryKey(user);
    }

    @Override
    public int save(User user) {
        UserExample example = new UserExample();
        example.createCriteria().andUserNameEqualTo(user.getUserName());
        List<User> list = userDao.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            return userDao.insert(user);
        }
        return 0;
    }

    @Override
    public int delete(Integer id) {
        return userDao.deleteByPrimaryKey(id);
    }
}
